## db_connector.py
import pymysql
from typing import Dict, Optional

class DatabaseConnectionError(Exception):
    """Custom exception for database connection errors."""
    pass

class QueryExecutionError(Exception):
    """Custom exception for query execution errors."""
    pass

class DBConnector:
    def __init__(self, connection_params: Optional[Dict[str, str]] = None):
        default_params = {
            'host': 'localhost',
            'user': 'root',
            'password': '',
            'db': 'test',
            'charset': 'utf8mb4'
        }
        self.connection_params = connection_params if connection_params else default_params

    def connect(self):
        """Establishes a connection to the database."""
        try:
            connection = pymysql.connect(**self.connection_params)
            return connection
        except pymysql.MySQLError as e:
            raise DatabaseConnectionError(f"Error connecting to the MySQL Database: {e}")

    def get_field_type(self, table_name: str, field_name: str) -> str:
        """Retrieves the data type of a specified field in a table."""
        try:
            with self.connect() as connection:
                with connection.cursor() as cursor:
                    query = "SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = %s AND COLUMN_NAME = %s"
                    cursor.execute(query, (table_name, field_name))
                    result = cursor.fetchone()
                    if result:
                        return result[0]
                    else:
                        return "Field not found"
        except DatabaseConnectionError:
            return "Connection error"
        except pymysql.MySQLError as e:
            raise QueryExecutionError(f"Error fetching field type from MySQL Database: {e}")
